package com.qf.fmall.service.impl;

import com.qf.fmall.dao.ShoppingCartMapper;
import com.qf.fmall.entity.Orders;
import com.qf.fmall.entity.ShoppingCart;
import com.qf.fmall.entity.ShoppingCartVo;
import com.qf.fmall.service.ShoppingCartService;
import com.qf.fmall.vo.ResStatus;
import com.qf.fmall.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service("shoppingCartService")
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo addCartTo(ShoppingCart shoppingCart) {
        ResultVo resultVo = new ResultVo();
        if (Objects.isNull(shoppingCart)) {
            resultVo.setCode(ResStatus.NO);
            return resultVo;
        }
        ;
        shoppingCart.setCartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        int insert = shoppingCartMapper.insert(shoppingCart);
        if (insert > 0) {
            resultVo.setCode(ResStatus.OK);
        } else {
            resultVo.setCode(ResStatus.NO);
        }
        return resultVo;
    }

    @Override
    public ResultVo listByUserId(Integer userId) {
        List<ShoppingCartVo> list = shoppingCartMapper.listByUserId(userId);
        ResultVo resultVo = new ResultVo();
        if ((list.size() == 0)) {
            resultVo.setCode(ResStatus.NO);
        } else {
            resultVo.setCode(ResStatus.OK);
            resultVo.setData(list);
        }
        return resultVo;
    }

    @Override
    public ResultVo updateCart(Integer cid, Integer cnum) {
        Integer i = shoppingCartMapper.updateCart(cid, cnum);
        ResultVo resultVo = new ResultVo();
        if (i == 0) {
            resultVo.setCode(ResStatus.NO);
            resultVo.setMsg("更新购物车失败");
        } else {
            resultVo.setCode(ResStatus.OK);
            resultVo.setMsg("success");
        }
        return resultVo;
    }

    @Override
    public ResultVo listByCids(String cids) {
        String[] split = cids.split(",");
        List<String> list = Arrays.asList(split);
        List<ShoppingCartVo> listByCids = shoppingCartMapper.listByCids(list);
        ResultVo resultVo = new ResultVo();
        if ((listByCids.size() == 0)) {
            resultVo.setCode(ResStatus.NO);
        } else {
            resultVo.setCode(ResStatus.OK);
            resultVo.setData(listByCids);
        }
        return resultVo;
    }

}
